package com.youan.pangu.core.mvc.configuration;

import com.youan.pangu.core.mvc.handler.GlobalErrorHandler;
import com.youan.pangu.core.mvc.handler.JsonReturnValueHandler;
import com.youan.pangu.core.mvc.interceptor.NoViewHandlerInterceptor;
import com.youan.pangu.core.mvc.interceptor.ShowRequestParamtersHandlerInterceptor;
import com.youan.pangu.core.mvc.resolver.LoginInfoMethodArgumentResolver;
import org.hibernate.validator.HibernateValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.List;

/**
 * 基本的MVC配置类
 */
public class BaseMvcConfiguration implements WebMvcConfigurer {
    @Override
    public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> handlers) {
        // 返回json格式返回值
        handlers.add(new JsonReturnValueHandler());
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 显示controller请求的入参
        registry.addInterceptor(new ShowRequestParamtersHandlerInterceptor());
        // controller层返回void或者字符串处理
        registry.addInterceptor(new NoViewHandlerInterceptor());
    }

    @Override
    public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
        //  异常统一处理
        //  resolvers.add(new SimpleExceptionResolver());
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        //  自动注入登陆信息
        resolvers.add(new LoginInfoMethodArgumentResolver());
    }

    //  全局异常处理
    @Bean
    public GlobalErrorHandler globalErrorHandler(){
        return new GlobalErrorHandler();
    }

    /**
     * 验证模块配置
     * @return
     */
    @Bean
    public Validator validator(){
        ValidatorFactory validatorFactory = Validation.byProvider( HibernateValidator.class )
                .configure()
                //开启快速校验--默认校验所有参数，false校验全部
                .addProperty( "hibernate.validator.fail_fast", "true" )
                .buildValidatorFactory();
        Validator validator = validatorFactory.getValidator();

        return validator;
    }

}
